import { baseHost } from '../config'
import jsonxml from 'jsontoxml'
import xml2json from 'xmlstring2json'
import fly from '../request'
import wx from '../wx'

let host =
	baseHost + 'iconographyApi/platform/iconographyPlatform/webService?wsdl'

let iconographyPost = (api, params) => {
	let resultArray = []
	Object.entries(params).forEach(item => {
		resultArray.push({
			name: item[0],
			text: item[1]
		})
	})
	let obj = [
		{
			name: api,
			attrs: { xmlns: 'urn:ihe:iti:xds-b:2007' },
			children: [
				{
					DocumentRequest: resultArray
				}
			]
		}
	]
	let xml = jsonxml(obj)
	let soap = `<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://webservice.platform.iconography.wonders.com/"><soapenv:Header/><soapenv:Body><web:registryStoredQueryList>><xml><![CDATA[${xml}]]></xml>
      </web:registryStoredQueryList>
   </soapenv:Body>
</soapenv:Envelope>`
	return new Promise((resolve, reject) => {
		fly
			.post(host, soap, {
				headers: {
					'Content-Type': 'text/xml; charset=utf-8'
				}
			})
			.then(response => {
				resolve(
					JSON.parse(
						xml2json(response.data)['soap:Envelope']['soap:Body'][
							'ns2:registryStoredQueryListResponse'
						].return['#text']
					)
				)
			})
			.catch(error => {
				wx.showToast({
					title: error
				})
				reject(error)
			})
	})
}

let getIconographyList = params => {
	return iconographyPost('RegistryStoredQueryListRequest', params)
}

export default {
	getIconographyList // 获取影像云列表
}
